package com.mine.frame.mylandemo.ui.haobo

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.util.Log
import android.view.WindowManager
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.mine.frame.common.base.BaseActivity
import com.mine.frame.mylandemo.R
import com.mine.frame.mylandemo.adapter.haobo.KeyNumberListAdapter
import com.mine.frame.mylandemo.entity.haobo.KeyNumberBean
import com.mine.frame.mylandemo.mvp.iview.IHaoBo
import com.mine.frame.mylandemo.mvp.presenter.HaoBoPresenter
import com.mine.frame.mylandemo.ui.dialog.ConfigDialog
import com.mine.frame.mylandemo.ui.dialog.CreateNameDialog
import com.mine.frame.mylandemo.ui.dialog.HaoBoMenuDialog
import com.mine.frame.mylandemo.ui.dialog.LoadingDialog
import com.third.device.mg.serialport.MGSerialPort
import com.third.device.mg.serialport.listener.MGNettyConnectListener
import com.third.device.mg.serialport.utils.send.MGSendUtils
import com.third.device.mg.serialport.utils.toHexString
import kotlinx.android.synthetic.main.atv_haobo.*

/**
 * @Date 2022/6/10
 * Description:
 */
class HaoBoInfraredAtv : BaseActivity<IHaoBo, HaoBoPresenter>(), IHaoBo, MGNettyConnectListener {
    private val setDialog by lazy { HaoBoMenuDialog(this) }

    private var ipAddress = "192.168.0.120" //IP地址
    private var port = 61233 //端口号


    private val loadDialog by lazy { LoadingDialog(this) }
    private val nameDialog by lazy { CreateNameDialog(this) }
    private val configDialog by lazy { ConfigDialog(this) }

    private var what = 0

    private var name = ""

    private val listData = mutableListOf<KeyNumberBean>()
    private val mAdapter by lazy { KeyNumberListAdapter() }
    companion object {
        const val TAG = "HaoBoInfraredAtv"
    }

    override fun initLayoutId(): Int = R.layout.atv_haobo

    override fun initPresenter(): HaoBoPresenter = HaoBoPresenter(this)

    override fun initLayoutAfter(savedInstanceState: Bundle?) {
        MGSendUtils.instance.initUtils(application, this)
        initRecycler()
        ClickUtils.applySingleDebouncing(btnSet) {
            initIPPort()
            if (!setDialog.isShowing) {
                setDialog.show()
            }
            setDialog.setBtnClickListener {
                what = it.id
                when (what) {
                    R.id.btnLearn -> {//学习指令
                        onLearn()
                    }
                    R.id.btnLearnLast -> {//最近学习过遥控器的序号

                    }
                    R.id.btnClearNumber -> {//清楚所有按键数据
                        if (!configDialog.isShowing){
                            configDialog.show()
                        }
                        configDialog.setInfoStr("是否清空按键信息?")
                        configDialog.setBtnClickListener {
                            val clear = MGSerialPort.instance.getHaoBo().getInfraredDev().getClearNumber()
                            MGSendUtils.instance.sentCommand(ipAddress, port, clear)
                        }
                    }
                    R.id.btnBps -> {//修改波特率

                    }
                    R.id.btnSave -> {//备份红外数据

                    }
                    R.id.btnReset -> {//恢复出厂设置

                    }

                }
            }
        }

        edtIP.text = Editable.Factory.getInstance().newEditable(ipAddress)
        edtPort.text = Editable.Factory.getInstance().newEditable(port.toString())
    }


    private fun onLearn() {
        if (!nameDialog.isShowing) {
            nameDialog.show()
            //使editext可以唤起软键盘
            nameDialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        }
        nameDialog.setBtnClickListener {
            name = it.toString()
            val learn = MGSerialPort.instance.getHaoBo().getInfraredDev().getLearn()
            MGSendUtils.instance.sentCommand(ipAddress, port, learn)
            showDialog()
        }
    }



    private fun initRecycler(){
        listData.clear()
        listData.addAll(mPresenter.getKeyNumberList())
        mRecycler.adapter = mAdapter
        mAdapter.setNewInstance(listData)
        mAdapter.setOnItemClickListener { _, _, position ->
            initIPPort()
            val bean = mAdapter.data[position]
            Log.e(TAG ,"发送:SIR${bean.number}  -- Int:${bean.getNumberInt()}")
            val command = MGSerialPort.instance.getHaoBo().getInfraredDev().getSend(bean.getNumberInt())
            MGSendUtils.instance.sentCommand(ipAddress, port, command)
        }
    }


    override fun connectBack(ip: String, port: Int) {
        Log.e(TAG, "connectBack : $ip:$port")

    }

    override fun disconnectBack(ip: String, port: Int) {
        Log.e(TAG, "disconnectBack : $ip:$port")
    }

    override fun readBack(ip: String, port: Int, result: ByteArray) {
        Log.e(TAG, "readBack : $ip:$port")
        Log.e(TAG, "readBack : ${result.toHexString()}")
        Log.e(TAG, "readBack : ${String(result)}")
        mPresenter.parseData(result)
    }

    override fun writeBack(ip: String, port: Int, successful: Boolean, data: ByteArray) {
        Log.e(TAG, "writeBack : $ip:$port")
        Log.e(TAG, "writeBack : $successful : ${data.toHexString()}")
    }

    override fun errorBack(ip: String, port: Int, error: Throwable) {
        Log.e(TAG, "errorBack : $ip:$port  ${error.message}")
    }

    private fun showDialog() {
        if (!loadDialog.isShowing) {
            loadDialog.show()
        }
        loadDialog.setHint("")
    }

    private fun hintDialog() {
        if (loadDialog.isShowing) {
            loadDialog.dismiss()
        }
    }

    override fun getWhat(): Int = what
    override fun getName(): String = name

    override fun updateHint(txt: CharSequence) {
        loadDialog.setHint(txt)
    }

    override fun dismissLoading() {
        hintDialog()
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onLearnSuccess(list:MutableList<KeyNumberBean>) {
        listData.clear()
        listData.addAll(list)
        mAdapter.notifyDataSetChanged()
        dismissLoading()
        SnackbarUtils.with(edtIP).setMessage("学习指令成功").showSuccess()
    }


    private fun initIPPort(){
        KeyboardUtils.hideSoftInput(this)
        if (edtIP.text.isNullOrEmpty()){
            SnackbarUtils.with(edtIP).setMessage("请输入IP地址").showWarning()
            return
        }else{
            ipAddress = edtIP.text.toString()
        }

        if (edtPort.text.isNullOrEmpty()){
            SnackbarUtils.with(edtIP).setMessage("请输入端口号").showWarning()
            return
        }else{
            port =edtPort.text.toString().toInt()
            if (port < 1 || port > 65535){
                SnackbarUtils.with(edtIP).setMessage("端口号异常(1,65535)").showWarning()
                return
            }
        }
        if (ipAddress.isEmpty()){
            SnackbarUtils.with(edtIP).setMessage("IP地址异常").showError()
            return
        }
    }
}